<template>
  <div>
    <el-table-form ref="form" :model="query">
      <el-form-item class="merge-item">
        <el-select v-model="searchType" style="width: 170px; margin-right: 2px;">
          <el-option value="billCode" label="气瓶回收单号" />
          <el-option value="csmCode" label="客户编号" />
          <el-option value="csmName" label="客户名称" />
        </el-select>
        <el-input v-model.trim="searchText" placeholder="请输入" clearable @keyup.enter.native="search" />
      </el-form-item>
      <el-form-item label="客户类型:" prop="csmType">
        <el-select v-model="query.csmType" clearable filterable placeholder="请选择">
          <el-option v-for="(item, index) in customerTypeMap" :key="index" :label="item.desc" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="状态" prop="billStatus">
        <el-select v-model="query.billStatus" filterable clearable placeholder="请选择">
          <el-option
            v-for="item in billStatusMap"
            :key="item.value"
            :value="item.value"
            :label="item.desc"
          />
        </el-select>
      </el-form-item>
      <el-form-item :table-form-merge="2" class="merge-item">
        <el-select v-model="dateType" style="width: 150px; margin-right: 2px;">
          <el-option value="createTime" label="回收时间" />
          <el-option value="cancelTime" label="作废时间" />
          <!-- <el-option value="auditDt" label="作废审核时间" /> -->
        </el-select>
        <el-date-picker
          v-model="queryDate"
          type="datetimerange"
          range-separator="至"
          start-placeholder="开始日期"
          end-placeholder="结束日期"
          unlink-panels
          :clearable="false"
          :default-time="['00:00:00', '23:59:59']"
        />
      </el-form-item>
      <template v-slot:btns>
        <el-button v-permission="[30801, 1]" type="primary" icon="el-icon-search" @click="search">查询</el-button>
      </template>
    </el-table-form>
    <div style="margin-bottom: 10px;">
      <div>
        <el-button v-permission="[30801, 3]" type="primary" icon="el-icon-download" @click="exportFile">导出</el-button>
      </div>
    </div>
    <lb-table
      ref="lbTable"
      v-loading="$loadingPlugin.fetchData"
      v-el-height-adaptive-table="{ bottomOffset: 10 }"
      border
      height="250"
      highlight-current-row
      element-loading-text="加载中"
      :column="columns"
      :data="tableData.data"
      pagination
      :total="tableData.total"
      custom-column
      @fetch="fetchData"
    />
    <!-- 气瓶回收抽屉 -->
    <CylinderRecoveryDetail
      ref="cylinderRecoveryDetail"
      :parent-fetch-data="refresh"
      :tree-data="treeData"
      :calc-type-list="calcTypeList"
      :paymen-fil-list="paymenFilList"
      :group-type-map="groupTypeMap"
    />
  </div>
</template>

<script>
  import dayjs from 'dayjs'
  import { cylinderRecoveryQuery, cylinderRecoveryListExport, queryExportDomain, cylinderRecoveryCancel } from '@/api'
  import { formatColumnMap } from '@/utils'
  import { mergeAsyncFunc } from '@/utils/mergeAsyncFunc'
  import { mapGetters } from 'vuex'
  import CylinderRecoveryDetail from './components/CylinderRecoveryDetail.vue'
  import {
    queryMap
  } from '@/api'
  export default {
    name: 'cylinderRecovery', // 气瓶回收
    components: {
      CylinderRecoveryDetail
    },
    data() {
      return {
        exportDomain: '', // 导出域名
        searchType: 'csmCode',
        searchText: '',
        actionColWidth: 80,
        searchParams: {},
        query: {
          csmType: '',
          billStatus: ''
        },
        queryDate: [],
        treeData: [],
        tableData: {
          total: 0,
          data: []
        },
        customerTypeMap: [], // 客户类型
        billStatusMap: [], // 气瓶状态
        calcTypeList: [],
        paymenFilList: [],
        groupTypeMap: [],
        dateType: 'createTime'
      }
    },
    computed: {
      ...mapGetters(['orgList']),
      columns: function() {
        return [
          {
            type: 'index'
          },
          {
            prop: 'billCode',
            width: 160,
            label: '气瓶回收单号',
            render: (h, { row }) => <el-link underline={false} onClick={() => this.openCylinderRecoveryDetail(row)}>{row.billCode}</el-link>
          },
          {
            prop: 'csmCode',
            label: '客户编号',
            width: 105
          },
          {
            prop: 'csmName',
            width: 120,
            label: '客户名称'
          },
          {
            prop: 'csmType',
            label: '客户类型',
            width: 140,
            render: (h, { row }) => <span>{row.csmType && formatColumnMap(this.customerTypeMap, 'value', row.csmType, 'desc')}</span>
          },
          {
            prop: 'totalNumber',
            label: '回收数量',
            width: 120
          },
          {
            prop: 'reclTotalAmount',
            label: '回收合计金额(元)',
            width: 130,
            render: (h, { row }) => <span>{ row.reclTotalAmount !== undefined ? row.reclTotalAmount.toFixed(2) : '' }</span>
          },
          {
            prop: 'targetUser',
            label: '回收人',
            width: 120
          },
          {
            label: '回收时间',
            prop: 'happendTime',
            width: 180,
            render: (h, { row }) => (
            <span>
              {row.happendTime && dayjs(row.happendTime).format('YYYY-MM-DD HH:mm')}
            </span>
          )
          },
          {
            prop: 'remark',
            width: 200,
            label: '备注'
          },
          {
            prop: 'billStatus',
            label: '状态',
            render: (h, { row }) => (
              <span>
                { row.billStatus ? formatColumnMap(this.billStatusMap, 'value', row.billStatus, 'desc') : '' }
              </span>
            )
          },
          {
            prop: 'cancelUserName',
            label: '作废人'
          },
          {
            label: '作废时间',
            prop: 'cancelTime',
            width: 180,
            render: (h, { row }) => (
            <span>
              {row.cancelTime && dayjs(row.cancelTime).format('YYYY-MM-DD HH:mm')}
            </span>
          )
          },
          {
            label: '操作',
            width: '80px',
            fixed: 'right',
            render: (h, { row }, $index) => {
              return (
                <div>
                  { row.billStatus === 4 && (<el-link v-show={this.$btnPermission([30801, 2])} type='danger' underline={false} size='mini' onClick={() => this.handleCancel(row)}>作废</el-link>)}
                </div>
              )
            }
          }
        ]
      }
    },
    async created() {
      await Promise.all([this.queryOptionsMap(), this.getExportDomain()])
    },
    methods: {
      // 获取导出域名
      getExportDomain() {
        mergeAsyncFunc(queryExportDomain)
          .then((res) => {
            this.exportDomain = res.data
          })
      },
      // 查询枚举 客户类型
      async queryOptionsMap() {
        const [res1, res2] = await Promise.all([
          mergeAsyncFunc(queryMap, { enumName: 'CustomerType' }),
          mergeAsyncFunc(queryMap, { enumName: 'RecycleBillStatus' })
        ])
        this.customerTypeMap = res1.data
        this.billStatusMap = res2.data
      },
      _getQuery(obj) {
        const query = {}
        for (const key in obj) {
          if (obj.hasOwnProperty(key)) {
            if (obj[key] !== '') {
              query[key] = obj[key]
            }
          }
        }
        return query
      },
      search() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      refresh() {
        this.$refs.lbTable.fetch({ currentPage: 1 })
      },
      async fetchData({ currentPage = 1, pageSize = 20 }) {
        const query = {
          ...this._getQuery(this.query),
          currentPage,
          pageSize
        }
        query[this.searchType] = this.searchText ? this.searchText : ''
        if (this.queryDate && this.queryDate.length > 0) {
          query[this.dateType] = this.queryDate[0]
          query[this.dateType + 'End'] = this.queryDate[1]
        }
        const res = await cylinderRecoveryQuery(query)
        this.searchParams = query
        this.tableData.data = res.data.rows
        if (currentPage === 1) this.tableData.total = res.data.total
        this.flexColumnWidth()
      },
      // 自适应表格列宽
      flexColumnWidth() {
        this.$nextTick(() => {
          let max = 0
          const actionColDom = document.getElementsByClassName('action-col')
          for (let i = 0; i < actionColDom.length; i++) {
            if (actionColDom[i].tagName === 'TD') {
              let width = 20
              const linkDom = actionColDom[i].childNodes[0].childNodes[0].childNodes
              linkDom.forEach(it => {
                width += (it.offsetWidth + 10)
              })
              if (width > max) max = width
            }
          }
          this.actionColWidth = max > 60 ? max - 10 : 50
        })
      },
      // 导出
      async exportFile() {
        const _this = this
        this.$confirm(`确定导出数据？`, '提示', {
          type: 'warning'
        }).then(() => {
          const copyColumn = JSON.parse(JSON.stringify(this.columns))
          copyColumn.pop() // 删除操作列
          const str = {}
          copyColumn.forEach(item => {
            str[item.prop] = item.label
          })
          cylinderRecoveryListExport({
            paramInfo: _this.searchParams,
            kv: str // 表格列
          }).then((res) => {
            window.open(`${_this.exportDomain}/page/export/frame?key=${res.data}`, '_blank')
          })
        })
      },
      async openCylinderRecoveryDetail(row) {
        await this.$refs.cylinderRecoveryDetail.open(row)
      },
      handleCancel(row) {
        this.$confirm('请确认是否要进行作废操作？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).then(async() => {
          const res = await cylinderRecoveryCancel({ billCode: row.billCode })
          if (res) {
            this.$message.success('操作成功！')
            this.search()
          }
        }).catch(() => {
          this.$message({
            type: 'info',
            message: '已取消操作'
          })
        })
      }
    }
  }
</script>

<style lang="scss" scoped></style>
